﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace TcpTest
{
    /// <summary>
    /// TcpClient操作
    /// </summary>
    public class TcpClientBusiness
    {
        #region    自定义参数
        /// <summary>
        /// Tcp客户端模型
        /// </summary>
        private static TcpClient tcpClient;
        /// <summary>
        /// 网络访问数据流
        /// </summary>
        private static NetworkStream networkStream;

        /// <summary>
        /// 返回数据
        /// </summary>
        public static List<byte[]> ResponseBytes = new List<byte[]>();

        /// <summary>
        /// 远程服务IP地址
        /// </summary>
        public static string RemoteIp = string.Empty;
        /// <summary>
        /// 远程服务IP地址对应端口
        /// </summary>
        public static int RemotePort = -1;

        /// <summary>
        /// 是否连接
        /// </summary>
        public static bool IsConnected = false;
        #endregion

        /// <summary>
        /// 打开TCP连接
        /// </summary>
        public static void ConnectToServer()
        {
            try
            {
                //初始化TCP客户端对象
                tcpClient = new TcpClient();
                //开始连接
                tcpClient.BeginConnect(RemoteIp, RemotePort, new AsyncCallback(AsynConnect), tcpClient);
            }
            catch (Exception ex)
            {
                Console.WriteLine("TcpClientBusiness", "ConnectToServer|异常消息：" + ex.Message.ToString());
            }
        }

        /// <summary>
        /// 异步连接
        /// </summary>
        /// <param name="iar"></param>
        public static void AsynConnect(IAsyncResult iar)
        {
            try
            {
                //连接成功
                tcpClient.EndConnect(iar);
                //连接成功标志
                IsConnected = true;
                networkStream = tcpClient.GetStream();
                byte[] TempBytes = new byte[1024];
                //开始异步读取返回数据
                networkStream.BeginRead(TempBytes, 0, TempBytes.Length, new AsyncCallback(AsynReceiveData), TempBytes);
                Console.WriteLine(Encoding.UTF8.GetString(TempBytes));
            }
            catch (Exception ex)
            {
                Console.WriteLine("TcpClientBusiness", "AsynConnect|异常消息：" + ex.Message.ToString());
            }
        }

        /// <summary>
        /// 发送数据
        /// <param name="SendBytes">需要发送的数据</param>
        /// </summary>
        public static void SendData(byte[] SendBytes)
        {
            try
            {
                if (networkStream.CanWrite && SendBytes != null && SendBytes.Length > 0)
                {
                    //发送数据
                    networkStream.Write(SendBytes, 0, SendBytes.Length);
                    networkStream.Flush();
                }
            }
            catch (Exception ex)
            {
                if (tcpClient != null)
                {
                    tcpClient.Close();
                    //关闭连接后马上更新连接状态标志
                    IsConnected = false;
                }
                Console.WriteLine("TcpClientBusiness", "SendData|异常消息：" + ex.Message.ToString());
            }
        }

        /// <summary>
        /// 异步接受数据
        /// </summary>
        /// <param name="iar"></param>
        public static void AsynReceiveData(IAsyncResult iar)
        {
            byte[] CurrentBytes = (byte[])iar.AsyncState;
            try
            {
                //结束了本次数据接收
                int num = networkStream.EndRead(iar);
                //这里展示结果为InfoModel的CurrBytes属性，将返回的数据添加至返回数据容器中
                ResponseBytes.Add(CurrentBytes);
                //处理结果后马上启动数据异步读取【目前我每条接收的字节数据长度不会超过1024】
                byte[] NewBytes = new byte[1024];
                networkStream.BeginRead(NewBytes, 0, NewBytes.Length, new AsyncCallback(AsynReceiveData), NewBytes);
            }
            catch (Exception ex)
            {
                Console.WriteLine("TcpClientBusiness", "AsynReceiveData|异常消息：" + ex.Message.ToString());
            }
        }
    }
}
